import { request } from "./httpHelper";
import { getLocalStorage, setLocalStorage } from "./localStorageHelper";
import { getNeurons } from "./tdengineApi";

const username = "admin";
const password = "0000";
const login_url = "/api/v2/login";
const ping_url = "/api/v2/ping";
const node_url = "/api/v2/node";
const node_set_url = "/api/v2/node/setting";
const node_control_url = "/api/v2/node/ctl";
const node_state_url = "/api/v2/node/state";
const group_url = "/api/v2/group";
const tag_url = "/api/v2/tags";
const write_url = "/api/v2/write";
const read_url = "/api/v2/read";
const pulgin_url = "/api/v2/plugin";
const subscribe_url = "/api/v2/subscribe";
const schema_url = "/api/v2/schema";
const log_url = "/api/v2/log";
const version_url = "/api/v2/version";

// 登录
const login = async (hosts) => {
  if (hosts) {
    hosts.forEach(async (element) => {
      let host = transform(element);

      let data = JSON.stringify({
        name: username,
        pass: password,
      });

      let config = {
        method: "post",
        url: host + login_url,
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };

      let response = await request(config);
      if (response && response != "") {
        setLocalStorage(host, response.token);
      }
    });
  }
};

// 根据neuron获取node
const getNodes = async (host) => {
  host = transform(host);
  if (host) {
    let token = getLocalStorage(host);

    if (token) {
      let config = {
        method: "get",
        url: host + node_url,
        headers: {
          Authorization: "Bearer " + token,
        },
        params: {
          type: 1,
        },
      };

      let response = await request(config);

      let nodes = response.nodes.map((v) => {
        return {
          label: v.name,
          value: v.name,
        };
      });

      return nodes;
    }
  }
};

// 根据neuron和node获取group
const getGroups = async (host, node) => {
  host = transform(host);
  if (host && node) {
    let token = getLocalStorage(host);

    if (token) {
      let config = {
        method: "get",
        url: host + group_url,
        headers: {
          Authorization: "Bearer " + token,
        },
        params: {
          node: node,
        },
      };

      let response = await request(config);

      let groups = response.groups.map((v) => {
        return {
          label: v.name,
          value: v.name,
        };
      });

      return groups;
    }
  }
};

// 根据neuron,node和group获取点位
const getTags = async (host, node, group) => {
  if (host && node && group) {
    host = transform(host);

    if (host) {
      let token = getLocalStorage(host);

      if (token) {
        let config = {
          method: "get",
          url: host + tag_url,
          headers: {
            Authorization: "Bearer " + token,
          },
          params: {
            node: node,
            group: group,
          },
        };

        let response = await request(config);

        let tags = response.tags.map((v) => {
          return {
            label: v.name,
            value: v.name,
          };
        });

        return tags;
      }
    }
  }
};

// ping
const ping = async (host) => {
  if (host) {
    host = transform(host);
    let config = {
      method: "post",
      url: host + ping_url,
      // headers: {
      //   Authorization: "Bearer " + token,
      // },
    };

    let response = await request(config);
    return response instanceof Object;
  }
  return false;
};

// 查询node运行状态
const getNodeStatus = async (host) => {
  if (host) {
    let token = getLocalStorage(transform(host));
    if (!token) {
      await login([host]);
      token = getLocalStorage(transform(host));
    }
    if (token) {
      host = transform(host);
      let config = {
        method: "get",
        url: host + node_state_url,
        headers: {
          Authorization: "Bearer " + token,
        },
      };

      let response = await request(config);
      return response.states;
    }
  }
};

// 查询group和tag数量
const getGroupAndTag = async (host) => {
  if (host) {
    let token = getLocalStorage(transform(host));
    if (!token) {
      await login([host]);
      token = getLocalStorage(transform(host));
    }
    if (token) {
      host = transform(host);
      let config = {
        method: "get",
        url: host + group_url,
        headers: {
          Authorization: "Bearer " + token,
        },
      };

      let response = await request(config);
      return response.groups;
    }
  }
};

// 查询运行状态
const getStatus = async () => {
  let neuron_online_total = 0;
  let neuron_total = 0;
  let node_online_total = 0;
  let node_total = 0;
  let group_total = 0;
  let tag_total = 0;
  let neurons = await getNeurons(undefined, 0, 0);
  neuron_total = neurons.total;

  let length = neurons.data.length;

  for (let index = 0; index < length; index++) {
    const neuron = neurons.data[index];
    let host = neuron.nhost;
    let online = await ping(host);
    if (online) {
      let token = getLocalStorage(transform(host));
      if (!token) {
        await login([host]);
        token = getLocalStorage(transform(host));
      }
      if (token) {
        neuron_online_total++;
        let nodes = await getNodes(host);
        node_total += nodes.length;
        let nodes_status = await getNodeStatus(host);
        for (let i = 0; i < nodes.length; i++) {
          const node_name = nodes[i].value;
          let node_status = nodes_status.filter((v) => v.node === node_name);
          if (node_status.length > 0) {
            if (node_status[0].running == 3 && node_status[0].link == 1) {
              node_online_total++;
            }
          }
        }

        let groups_and_tags = await getGroupAndTag(host);
        group_total += groups_and_tags.length;
        for (let j = 0; j < groups_and_tags.length; j++) {
          tag_total += groups_and_tags[j].tag_count;
        }
      }
    }
  }

  return {
    neuron_online_total,
    neuron_total,
    node_online_total,
    node_total,
    group_total,
    tag_total,
  };
};

// host转换成api
const transform = (host) => {
  host = String(host);
  let ip = "";
  let port = "";

  if (host) {
    if (host.startsWith("http")) {
      host = host.split("//")[1];
    }

    try {
      ip = host.split(":")[0];
      port = Number(String(host.split(":")[1]).replace("/", "")) + 1;

      host = "http://" + ip + ":" + port;
      return host;
    } catch (err) {
      console.log(err);
    }
  }
};

export { login, getNodes, getGroups, getTags, getStatus };
